// pages/submit_order/submit_order.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        primary: app.globalData.primary, // 主题色
        ossPath: app.globalData.ossPath,
        shopAddress: [], // 地址信息
        orderParam: {  // 提交订单参数
            InvoiceID: '',
            AddressID: '',
            ShippingTypeID: 1,
            CouponCode: '',
            RegionId: null,
            ShoppingCartItem: []
        },
        model: 'cart', // 进入模式 
        shoppingList: [],  //订单产品列表
        amount: 0,  // 产品总价格
        couponList: [],  // 可使用优惠券列表
        couponIndex: null,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //设置主题色
        if (app.globalData.primary) {
            this.setData({ primary: app.globalData.primary })
            app.usePrimary(app.globalData.primary)
        }
        if (options.model){
            this.setData({ model: options.model})
        }
    },
    goback: function() {
        wx.navigateBack()
    },
    getShopAddress: function() { // 获取地址
        wx.request({
            url: app.globalData.serverPath + '/shipaddresses?TeamNum=' + app.globalData.user.team,
            success: ({data}) => {
                var address = this.filterAddress(data)
                this.setData({
                    shopAddress: address
                })
            }
        })
    },
    filterAddress: function(data) { // 过滤地址
        if (data.length == 0) {
            this.data.orderParam.AddressID = ''
            this.data.orderParam.RegionId = null
        } else {
            var state = true;
            for(let i = 0; i < data.length; i++) {
                if (data[i].IsDefault) {
                    this.data.orderParam.AddressID = data[i].ShippingId
                    this.data.orderParam.RegionId = data[i].RegionId
                    state = false
                    break;
                }
            } 
            if (state) {
                this.data.orderParam.AddressID = data[0].ShippingId
                this.data.orderParam.RegionId = data[0].RegionId
                data[0].IsDefault = true;
            }
        }
        this.setData({ orderParam: this.data.orderParam})
        this.getCart()
        return data
    },
    getCart: function() { // 获取购物车
        var cart = wx.getStorageSync('cart');
        try {
            cart = JSON.parse(cart);
        } catch (err) {
            cart = []
        }
        this.data.orderParam.ShoppingCartItem = []
        if (cart.length) {
            if (this.data.model == 'cart') {
                cart.forEach((item, index) => {
                    if (item.Selected == 1) {
                        this.data.orderParam.ShoppingCartItem.push(item)
                    }
                })
            } else {
                this.data.orderParam.ShoppingCartItem.push(cart[0])
            }
            this.setData({
                orderParam: this.data.orderParam
            })
        }
        this.getOrderPrice(this.data.orderParam)
        
    },
    // 获取订单报价
    getOrderPrice(params) {
        if (params.RegionId == 0) {
            wx.showToast({
                title: '收货地址有误请重新填写',
                icon: 'none'
            })
        }
        wx.showLoading()
        wx.request({
            url: app.globalData.serverPath + '/ShoppingCar',
            method: 'post',
            header: { token: app.globalData.header.token },
            data: params,
            success: ({ data }) => {
                // this.couponList = data.CanUseCoupon
                data.ShoppingCartItem.forEach(item => {
                    item.TotalPrice = parseFloat(item.TotalPrice).toFixed(2)
                })
                this.setData({
                    amount: data.Amount,
                    shoppingList: data.ShoppingCartItem
                })
            },
            complete: ()=> wx.hideLoading()
        })
    },
    handleSubmit() { // 提交订单
        console.log(this.data.orderParam)
        //没有填写收货地址
        if (!this.data.orderParam.RegionId) { 
            wx.showToast({
                title: '请填写收货地址',
                icon: 'none'
            })
            return
        }

        //收货地址有误
        if (this.data.orderParam.RegionId === 0) {
            wx.showToast({
                title: '收货地址有误请重新填写',
                icon: 'none'
            })
            return
        }

        //商品信息不完整
        if (this.data.orderParam.ShoppingCartItem.length == 0) {
            wx.showToast({
                title: '没有商品信息请重新选择',
                icon: 'none'
            })
            return
        }

        wx.showLoading({
            mask: true,
            title: '提交订单中...',
        })
        
        wx.request({
            url: app.globalData.serverPath + '/SubmitOrder',
            method: 'post',
            header: {token: app.globalData.header.token},
            data: this.data.orderParam,
            success: ({data}) => {
                if (data.STATUS == "SUCCESS") {
                    if (this.data.model == 'cart') {
                        this.deleteCart(0)
                        this.data.orderParam.ShoppingCartItem = []
                    } else {
                        this.data.orderParam.ShoppingCartItem.forEach((item, index) => {
                            if (item.Selected == 1) {
                                this.deleteCart(index)
                            }
                        })
                    }
                    let ordercode = data.data.OrderCode
                    wx.navigateTo({
                        url: '../payment/index?orderCode=' + ordercode
                    })
                    app.setCartbadge();
                }
            },
            complete: () => wx.hideLoading()
        })
    },
    deleteCart: function (i) { // 删除购物车商品
        var cart = wx.getStorageSync('cart');
        cart = JSON.parse(cart)
        cart.splice(i, 1);
        var json = JSON.stringify(cart);
        wx.setStorageSync('cart', json)
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getShopAddress();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})